import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { getRoutes } from '@/api/system/router/RouterManager'
import useStore from '@/store'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/star-login',
    name: 'login',
    component: () => import('@/views/common/login/index.vue')
  },
  {
    path: '/',
    name: 'root',
    redirect: '/dashboard/base'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach(async (to, from, next) => {
  const whitelistRegex = /^\/(star-login)/

  // if (to.path !== '/star-login' && to.path !== '/' && to.path !== '/publish/form' && to.path !== '/publish/result') {
  if (!whitelistRegex.test(to.path)) {
    const { routerStore } = useStore()
    if (routerStore.routes.length < 1) {
      await getRoutes().then((data) => {
        routerStore.addRoutes(data, router)
        let newPath = to.path
        if (!router.getRoutes().find(item => item.path === newPath)) {
          if (router.getRoutes().find(item => item.path === '/dashboard/base')) {
            newPath = '/'
          } else {
            newPath = '/star-login'
          }
        }
        next({ ...to, path: newPath, replace: true })
      }).catch(_ => {
        next()
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
